// 填充用户信息
function populateUserInfo() {
  try {
    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    
    if (!who || !users) {
      throw new Error("User data not found");
    }
    
    const user = users.find(u => u.email === who.email);
    
    if (!user) {
      throw new Error("User not found in users list");
    }
    
    document.getElementById("nameInput").value = user.name || "";
    document.getElementById("location").value = user.location || ""; // 修正ID
    document.getElementById("weight").value = user.weight || "";     // 修正ID
  } catch (error) {
    console.error("Error populating user info:", error);
    alert("Failed to load user data. Please log in again.");
  }
}

// 编辑功能：启用输入框
function editProfile() {
  document.getElementById('personalInfoFields').disabled = false;
}

// 保存功能：更新本地存储
function saveProfile() {
  try {
    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    
    const user = users.find(u => u.email === who.email);
    
    // 更新用户数据
    user.name = document.getElementById('nameInput').value;
    user.location = document.getElementById('location').value;     // 修正ID
    user.weight = document.getElementById('weight').value;         // 修正ID
    
    // 更新本地存储
    localStorage.setItem("loggedinUser", JSON.stringify(user));
    localStorage.setItem("users", JSON.stringify(users));
    
    document.getElementById('personalInfoFields').disabled = true;
    alert("Personal Info Saved");
  } catch (error) {
    console.error("Error saving user info:", error);
    alert("Failed to save user data. Please try again.");
  }
}

// 页面加载时自动填充用户信息
document.addEventListener('DOMContentLoaded', populateUserInfo);